
package spider;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 参数处理类
 * 
 * @author menglili@wangamedia.com
 * @date 2015年12月9日
 */
public class ParameterUtil {

	/**
	 * @param params
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String getSignData(Map<String, String[]> params) throws UnsupportedEncodingException {
		StringBuilder content = new StringBuilder();
		// 按照key做排序
		List<String> keys = new ArrayList<String>(params.keySet());
		Collections.sort(keys);
		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			if ("sign".equals(key)) {
				continue;
			}
			String[] values = params.get(key);
			if (null == values) {
				continue;
			}
			for (String value : values) {
				if (value != null) {
					content.append((i == 0 ? "" : "&") + key + "=" + URLEncoder.encode(value, "utf-8"));
				} else {
					content.append((i == 0 ? "" : "&") + key + "=");
				}
			}
		}
		return content.toString();
	}

	public static String getSignDataString(Map<String, String> params) {
		StringBuilder content = new StringBuilder();
		// 按照key做排序
		List<String> keys = new ArrayList<String>(params.keySet());
		Collections.sort(keys);
		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			if ("sign".equals(key)) {
				continue;
			}
			String value = params.get(key);
			if (value != null) {
				content.append((i == 0 ? "" : "&") + key + "=" + value);
			} else {
				content.append((i == 0 ? "" : "&") + key + "=");
			}
		}
		return content.toString();
	}

	/**
	 * 将Map中的数据组装成url
	 * 
	 * @param params
	 *            参数按照字母排序
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String mapToUrl(Map<String, String[]> params) {
		StringBuilder sb = new StringBuilder();
		boolean isFirst = true;
		Iterator<Map.Entry<String, String[]>> iterator = params.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry<String, String[]> item = iterator.next();
			String key = item.getKey();
			String[] values = item.getValue();
			try {
				if (isFirst) {
					for (String value : values) {
						sb.append(key + "=" + URLEncoder.encode(value, "utf-8"));
					}
					isFirst = false;
				} else {
					for (String value : values) {
						if (value != null) {
							sb.append("&" + item.getKey() + "=" + URLEncoder.encode(value, "utf-8"));
						} else {
							sb.append("&" + item.getKey() + "=");
						}
					}
				}
			} catch (UnsupportedEncodingException e) {
				// e.printStackTrace();
			}
		}
		return sb.toString();
	}

	/**
	 * 取得URL中的参数值。
	 * <p>
	 * 如不存在，返回空值。
	 * </p>
	 * 
	 * @param url
	 * @param name
	 * @return
	 */
	public static String getParameter(String url, String name) {
		if (name == null || name.equals("")) {
			return null;
		}
		name = name + "=";
		int start = url.indexOf(name);
		if (start < 0) {
			return null;
		}
		start += name.length();
		int end = url.indexOf("&", start);
		if (end == -1) {
			end = url.length();
		}
		return url.substring(start, end);
	}

	public static void main(String[] args) {
		System.out.println(getUrlParams("a=1&b2"));
	}

	public static Map<String, String> getUrlParams(String queryStr) {
		Map<String, String> resMap = new HashMap<String, String>();
		if (null == queryStr || queryStr.length() == 0) {
			return resMap;
		}
		String[] tmp = queryStr.trim().split("&");

		for (String t : tmp) {
			// String[] tt = t.split("=");
			// if (tt.length == 2) {
			// resMap.put(tt[0], tt[1]);
			// }
			if (t.indexOf("=") != -1) {
				int p = t.indexOf("=");
				resMap.put(t.substring(0, p), t.substring(p + 1));
			}
		}
		return resMap;
	}

	/**
	 * 参数按照添加到map中的顺序进行排序
	 * 
	 * @param params
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String mapToUrlString(Map<String, String> params) throws UnsupportedEncodingException {
		StringBuilder sb = new StringBuilder();
		boolean isFirst = true;
		for (String key : params.keySet()) {
			String value = params.get(key);
			if (isFirst) {
				sb.append(key + "=" + URLEncoder.encode(value, "utf-8"));
				isFirst = false;
			} else {
				if (value != null) {
					sb.append("&" + key + "=" + URLEncoder.encode(value, "utf-8"));
				} else {
					sb.append("&" + key + "=");
				}
			}
		}
		return sb.toString();
	}

}